package pl.soulmusic.phylactery;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;

import pl.soulmusic.phylactery.db.DAO;
import pl.soulmusic.phylactery.map.GetSongsTask;
import pl.soulmusic.phylactery.map.Song;
import pl.soulmusic.phylactery.map.SongsOverlay;
import pl.soulmusic.phylactery.music.MusicService;
import pl.soulmusic.phylactery.soap.SendSongsTask;
import pl.soulmusic.phylactery.soap.ServiceInvoker;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.DhcpInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.MediaStore;
import android.speech.RecognizerIntent;
import android.text.format.Formatter;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;

public class Phylactery extends MapActivity implements OnTabChangeListener,
		OnClickListener {

	public static final String TAG = "Phylactery";

	// private static final String NO_ALBUM = "(no album)";
	// private static final String MIXED_ARTIST = "(mixed artist)";

	private static final String LIST_TAB_TAG = "List";
	private static final String MAP_TAB_TAG = "Map";
	private static final String PLAYER_TAB_TAG = "Player";
	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;

	private TabHost tabHost;

	private ListView libraryListView;
	private LinearLayout playerView;
	private ListView playlistView;
	private MapView map;

	// we want to be aware of our location
	private MyLocationOverlay locationOverlay;
	private LocationManager locationManager;
	private LocationListener locationListener;
	private boolean follow = false;
	private boolean onMap = false;

	private Button mPlayButton;
	private Button mPauseButton;
	private Button mSkipButton;
	private Button mRewindButton;
	private Button mStopButton;
	private Button mEjectButton;
	private Button mRecordGPSButton;

	private Boolean isBackAvailable;

	/**
	 * Get data from MediaStore about albums on the device.
	 */
	private void prepareAlbumList() {
		isBackAvailable = false;

		String[] columns = { MediaStore.Audio.Albums.ALBUM,
				MediaStore.Audio.Albums.ARTIST,
				MediaStore.Audio.Albums.NUMBER_OF_SONGS };

		ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

		Cursor cursor = managedQuery(
				MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, columns, null,
				null, null);

		if (cursor != null) {
			cursor.moveToFirst();
			while (!cursor.isAfterLast()) {
				HashMap<String, String> hash = new HashMap<String, String>();
				hash.put("album", cursor.getString(0));
				hash.put("artist", cursor.getString(1));
				hash.put("songs", String.valueOf(cursor.getInt(2)));
				list.add(hash);
				cursor.moveToNext();
			}
		}

		// add no album data
		// TODO: if file has no album it should be listed under "no album"

		SimpleAdapter adapter = new SimpleAdapter(this, list,
				R.layout.album_row_view, new String[] { "album", "artist",
						"songs" }, new int[] { R.id.album_title, R.id.artist,
						R.id.number_of_songs });

		libraryListView.setAdapter(adapter);

		libraryListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				@SuppressWarnings("unchecked")
				HashMap<String, String> entry = (HashMap<String, String>) libraryListView
						.getAdapter().getItem(position);
				if (entry != null) {
					prepareSongList(entry.get("album"), entry.get("artist"));
				}
			}
		});
	}

	/**
	 * Get data from MediaStore about songs of given artist/album
	 * 
	 * @param album
	 *            title of the album
	 * @param artist
	 *            name of the artist
	 */
	private void prepareSongList(String album, String artist) {
		isBackAvailable = true;

		String[] columns = { MediaStore.Audio.Media.TITLE,
				MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media._ID };

		String[] selectionArgs = { album, artist };
		String selection = MediaStore.Audio.Media.ALBUM + "=? AND "
				+ MediaStore.Audio.Media.ARTIST + "=? ";

		ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

		Cursor cursor = managedQuery(
				MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns,
				selection, selectionArgs, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			HashMap<String, String> hash = new HashMap<String, String>();
			hash.put("title", cursor.getString(0));
			Calendar cal = new GregorianCalendar();
			cal.setTimeInMillis(cursor.getInt(1));
			cal.add(Calendar.HOUR, -1);
			SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
			hash.put("duration", format.format(cal.getTime()));
			hash.put("id", cursor.getString(2));
			list.add(hash);
			cursor.moveToNext();
		}

		SimpleAdapter adapter = new SimpleAdapter(this, list,
				R.layout.song_row_view, new String[] { "title", "duration" },
				new int[] { R.id.song_title, R.id.duration });

		libraryListView.setAdapter(adapter);

		libraryListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				@SuppressWarnings("unchecked")
				HashMap<String, String> entry = (HashMap<String, String>) libraryListView
						.getAdapter().getItem(position);
				if (entry != null) {
					DAO dao = new DAO(getApplicationContext(), null);
					dao.addSongToPlaylist(Long.parseLong(entry.get("id")));
					preparePlayList();
				}
			}
		});
	}

	/**
	 * Get data from DB about songs on playlist
	 */
	private void preparePlayList() {
		DAO dao = new DAO(getApplicationContext(), null);

		// Force DB fix xD
		// getApplicationContext().deleteDatabase("pl.soulmusic.phylactery.db");

		ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		ArrayList<Long> playlist = dao.getPlaylist();

		for (int i = 0; i < playlist.size(); i++) {
			String[] columns = { MediaStore.Audio.Media.TITLE,
					MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media._ID };

			String[] selectionArgs = { String.valueOf(playlist.get(i)) };
			String selection = MediaStore.Audio.Media._ID + "=? ";

			Cursor cursor = managedQuery(
					MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns,
					selection, selectionArgs, null);

			// this should only loop 1 time for each query
			if (cursor == null)
				return;
			cursor.moveToFirst();
			while (!cursor.isAfterLast()) {
				HashMap<String, String> hash = new HashMap<String, String>();
				hash.put("title", cursor.getString(0));
				Calendar cal = new GregorianCalendar();
				cal.setTimeInMillis(cursor.getInt(1));
				cal.add(Calendar.HOUR, -1);
				SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
				hash.put("duration", format.format(cal.getTime()));
				hash.put("id", cursor.getString(2));
				list.add(hash);
				cursor.moveToNext();
			}
		}

		SimpleAdapter adapter = new SimpleAdapter(this, list,
				R.layout.song_row_view, new String[] { "title", "duration" },
				new int[] { R.id.song_title, R.id.duration });

		playlistView.setAdapter(adapter);
		registerForContextMenu(playlistView);

		playlistView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				@SuppressWarnings("unchecked")
				HashMap<String, String> entry = (HashMap<String, String>) playlistView
						.getAdapter().getItem(position);
				if (entry != null) {
					view.showContextMenu();
				}
			}
		});
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.playlist_menu, menu);

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		@SuppressWarnings("unchecked")
		HashMap<String, String> entry = (HashMap<String, String>) playlistView
				.getAdapter().getItem(info.position);
		if (entry != null) {
			menu.setHeaderTitle(entry.get("title"));
		} else
			menu.setHeaderTitle("Track options");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.menu_remove:
			@SuppressWarnings("unchecked")
			HashMap<String, String> entry = (HashMap<String, String>) playlistView
					.getAdapter().getItem(info.position);
			if (entry != null) {
				DAO dao = new DAO(getApplicationContext(), null);
				dao.removeSongFromPlaylist(Long.parseLong(entry.get("id")));
				preparePlayList();
			}
			return true;
		case R.id.menu_play_now:
			DAO dao = new DAO(getApplicationContext(), null);
			dao.setCurrentSongNumber(info.position);
			dao.setNextSongNumber(info.position);
			// HACKED :)
			// [PLAY dzia�a dla stanu stopped, SKIP dzia�a dla playing i paused]
			if (MusicService.mState == MusicService.State.Playing
					|| MusicService.mState == MusicService.State.Paused)
				startService(new Intent(MusicService.ACTION_SKIP));
			else
				startService(new Intent(MusicService.ACTION_PLAY));

			changePlayerButtons(true);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
		case KeyEvent.KEYCODE_HEADSETHOOK:
			event.startTracking();
			return true;
		case KeyEvent.KEYCODE_BACK:
			if (event.getRepeatCount() == 0) {
				if (tabHost.getCurrentTab() == 0) {
					if (isBackAvailable) {
						prepareAlbumList();
						return true;
					}
				}
			}
			break;
		case KeyEvent.KEYCODE_SEARCH:
			recognizeVoice();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
		case KeyEvent.KEYCODE_HEADSETHOOK:
			if (event.isTracking() && !event.isCanceled()) {
				startService(new Intent(MusicService.ACTION_TOGGLE_PLAYBACK));
				return true;
			}

		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	public boolean onKeyLongPress(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
		case KeyEvent.KEYCODE_HEADSETHOOK:
			recognizeVoice();
			return true;
		}
		return super.onKeyLongPress(keyCode, event);
	}

	/**
	 * Runs the voice recognition Activity
	 */
	private void recognizeVoice() {
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak control command");
		startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
	}

	/**
	 * Handle the results from the recognition activity.
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
				&& resultCode == RESULT_OK) {
			// fetching recognized result
			String result = data.getStringArrayListExtra(
					RecognizerIntent.EXTRA_RESULTS).get(0);

			if (result.equalsIgnoreCase("graj")
					|| result.equalsIgnoreCase("play"))
				onClick((View) mPlayButton);
			else if (result.equalsIgnoreCase("pauza")
					|| result.equalsIgnoreCase("pause"))
				onClick((View) mPauseButton);
			else if (result.equalsIgnoreCase("dalej")
					|| result.equalsIgnoreCase("next"))
				onClick((View) mSkipButton);
			else if (result.equalsIgnoreCase("cofnij")
					|| result.equalsIgnoreCase("back"))
				onClick((View) mRewindButton);
			else if (result.equalsIgnoreCase("zatrzymaj")
					|| result.equalsIgnoreCase("stop"))
				onClick((View) mStopButton);
			else if (result.equalsIgnoreCase("strumień")
					|| result.equalsIgnoreCase("stream"))
				onClick((View) mEjectButton);
			else if (result.equalsIgnoreCase("lista")
					|| result.equalsIgnoreCase("list"))
				tabHost.setCurrentTabByTag(LIST_TAB_TAG);
			else if (result.equalsIgnoreCase("odtwarzacz")
					|| result.equalsIgnoreCase("player"))
				tabHost.setCurrentTabByTag(PLAYER_TAB_TAG);
			else if (result.equalsIgnoreCase("mapa")
					|| result.equalsIgnoreCase("map"))
				tabHost.setCurrentTabByTag(MAP_TAB_TAG);
			else if (result.equalsIgnoreCase("wyjdź")
					|| result.equalsIgnoreCase("exit"))
				finish();

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	public void onClick(View target) {
		// Send the correct intent to the MusicService, according to the button
		// that was clicked
		if (target == mPlayButton) {
			startService(new Intent(MusicService.ACTION_PLAY));
			changePlayerButtons(true);
		} else if (target == mPauseButton) {
			startService(new Intent(MusicService.ACTION_PAUSE));
			changePlayerButtons(false);
		} else if (target == mSkipButton)
			startService(new Intent(MusicService.ACTION_SKIP));
		else if (target == mRewindButton)
			startService(new Intent(MusicService.ACTION_REWIND));
		else if (target == mStopButton) {
			startService(new Intent(MusicService.ACTION_STOP));
			changePlayerButtons(false);
		} else if (target == mRecordGPSButton)
			startService(new Intent(MusicService.ACTION_GPS));
		else if (target == mEjectButton) {
			Intent i = new Intent(MusicService.ACTION_URL);
			Uri uri = Uri
					.parse("http://www.vorbis.com/music/Epoq-Lepidoptera.ogg");
			i.setData(uri);
			startService(i);
			changePlayerButtons(true);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		mPlayButton = (Button) findViewById(R.id.playbutton);
		mPauseButton = (Button) findViewById(R.id.pausebutton);
		mSkipButton = (Button) findViewById(R.id.skipbutton);
		mRewindButton = (Button) findViewById(R.id.rewindbutton);
		mStopButton = (Button) findViewById(R.id.stopbutton);
		mEjectButton = (Button) findViewById(R.id.ejectbutton);
		mRecordGPSButton = (Button) findViewById(R.id.record_gps_button);

		mPlayButton.setOnClickListener(this);
		mPauseButton.setOnClickListener(this);
		mSkipButton.setOnClickListener(this);
		mRewindButton.setOnClickListener(this);
		mStopButton.setOnClickListener(this);
		mEjectButton.setOnClickListener(this);
		mRecordGPSButton.setOnClickListener(this);

		// setup for voice input
		// Check to see if a recognition activity is present
		PackageManager pm = getPackageManager();
		List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
				RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		if (activities.size() == 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Not Available");
			builder.setMessage("No recognition software installed.Download one?");
			builder.setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Intent marketIntent = new Intent(Intent.ACTION_VIEW);
							marketIntent.setData(Uri
									.parse("market://details?id=com.google.android.voicesearch"));
						}
					});
			builder.setNegativeButton("No", null);
			builder.create().show();
		}

		tabHost = (TabHost) findViewById(android.R.id.tabhost);

		// setup must be called if you are not inflating the tabhost from XML
		tabHost.setup();
		tabHost.setOnTabChangedListener(this);

		// setup list view
		libraryListView = (ListView) findViewById(R.id.LibraryList);
		libraryListView.setEmptyView((TextView) findViewById(R.id.LibraryText));

		// setup player View
		playerView = (LinearLayout) findViewById(R.id.Player);
		playlistView = (ListView) findViewById(R.id.PlaylistList);

		// add items to list view
		prepareAlbumList();

		// add items to playlist in player view
		preparePlayList();

		// setup my location
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationListener = new MyLocationListener(this);

		// setup map view
		map = (MapView) findViewById(R.id.mapview);
		map.setBuiltInZoomControls(true);
		map.getController().setZoom(18);

		locationOverlay = new MyLocationOverlay(this, map);
		GeoPoint myLoc = locationOverlay.getMyLocation();
		if (myLoc != null)
			map.getController().setCenter(myLoc);
		map.getOverlays().add(locationOverlay);

		// add views to tab host
		tabHost.addTab(tabHost
				.newTabSpec(LIST_TAB_TAG)
				.setIndicator("List",
						getResources().getDrawable(R.drawable.ic_tab_media))
				.setContent(new TabContentFactory() {
					public View createTabContent(String arg0) {
						return libraryListView;
					}
				}));
		tabHost.addTab(tabHost
				.newTabSpec(PLAYER_TAB_TAG)
				.setIndicator("Player",
						getResources().getDrawable(R.drawable.ic_tab_player))
				.setContent(new TabContentFactory() {
					public View createTabContent(String arg0) {
						return playerView;
					}
				}));
		tabHost.addTab(tabHost
				.newTabSpec(MAP_TAB_TAG)
				.setIndicator("Map",
						getResources().getDrawable(R.drawable.ic_tab_map))
				.setContent(new TabContentFactory() {
					public View createTabContent(String arg0) {
						return map;
					}
				}));

		// HACK to get the list view to show up first,
		// otherwise the mapview would be bleeding through and visible
		tabHost.setCurrentTab(2);
		tabHost.setCurrentTab(1);
		tabHost.setCurrentTab(0);

		updatePlayerButtons();

		WifiManager wifii = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		DhcpInfo d = wifii.getDhcpInfo();

		//ServiceInvoker.gateway = FormatIP(d.gateway);
		ServiceInvoker.gateway = "192.168.1.101";
	}

	public String FormatIP(int IpAddress) {
		return Formatter.formatIpAddress(IpAddress);
	}

	/*
	 * XML Menu
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		MenuInflater inflater = getMenuInflater();
		switch (tabHost.getCurrentTab()) {
		case 2:
			inflater.inflate(R.menu.menu, menu);
			break;
		case 1:
			inflater.inflate(R.menu.player_menu, menu);
		default:
			;
		}
		return true;
	}

	/*
	 * Menu click reaction
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case R.id.menu_satellite:

			if (map.isSatellite()) {
				map.setSatellite(false);
			} else {
				map.setSatellite(true);
			}

			return true;

		case R.id.menu_follow:
			if (follow) {
				locationManager.removeUpdates(locationListener);
				follow = false;
				Toast.makeText(getApplicationContext(),
						"Stopped following current position.",
						Toast.LENGTH_SHORT).show();
			} else {
				locationManager.requestLocationUpdates(
						LocationManager.GPS_PROVIDER, 0, 0, locationListener);
				follow = true;
				Toast.makeText(getApplicationContext(),
						"Started following current position.",
						Toast.LENGTH_SHORT).show();
			}

			return true;

		case R.id.menu_sync:
			SendSongsTask sendSongsTask = new SendSongsTask(this);
			sendSongsTask.execute();

			// ServiceInvoker.addTrack("test2", "3556498", 0, 0, "genreName",
			// "albumName", "albumYear", "artistName", "artistCountry",
			// "trackTitle", "trackYouUrl");
			// ServiceInvoker.addPOI("test2", "3556498", "name", "description",
			// 0, 0, 0)
			return true;

		case R.id.menu_clear:
			DAO dao = new DAO(getApplicationContext(), null);
			dao.clearPlaylist();
			preparePlayList();

			return true;
		case R.id.menu_clear_logged:
			DAO dao2 = new DAO(getApplicationContext(), null);
			dao2.clearLogged();
			makeSongsOverlay(new ArrayList<Song>());
			map.refreshDrawableState();

			return true;
		default:
			return super.onOptionsItemSelected(item);

		}

	}

	@Override
	public void onResume() {
		super.onResume();

		locationOverlay.enableMyLocation();
		locationOverlay.enableCompass();
		updatePlayerButtons();
	}

	@Override
	public void onPause() {
		super.onPause();

		locationOverlay.disableMyLocation();
		locationOverlay.disableCompass();
		updatePlayerButtons();
	}

	private void changePlayerButtons(boolean showPause) {
		if (showPause) {
			mPauseButton.setVisibility(Button.VISIBLE);
			mPlayButton.setVisibility(Button.GONE);
		} else {
			mPauseButton.setVisibility(Button.GONE);
			mPlayButton.setVisibility(Button.VISIBLE);
		}
		// DAO dao = new DAO(getApplicationContext(), null);
		// playlistView.setSelection(dao.getCurrentSongNumber());
	}

	private void updatePlayerButtons() {
		if (MusicService.mState == MusicService.State.Playing) {
			mPauseButton.setVisibility(Button.VISIBLE);
			mPlayButton.setVisibility(Button.GONE);
		} else {
			mPauseButton.setVisibility(Button.GONE);
			mPlayButton.setVisibility(Button.VISIBLE);
		}
		// DAO dao = new DAO(getApplicationContext(), null);
		// playlistView.setSelection(dao.getCurrentSongNumber());
	}

	/**
	 * From MapActivity, just has to be so.
	 * 
	 * @see com.google.android.maps.MapActivity#isRouteDisplayed()
	 */
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	/**
	 * Implement logic here when a tab is selected
	 * 
	 */
	public void onTabChanged(String tabName) {
		onMap = false;
		if (tabName == MAP_TAB_TAG) {
			onMap = true;
			GetSongsTask getSongsTask = new GetSongsTask(this);
			getSongsTask.execute();
			map.refreshDrawableState();
			return;
		}
		if (tabName == PLAYER_TAB_TAG) {
			preparePlayList();
			return;
		}

	}

	private class MyLocationListener implements LocationListener {

		private GeoPoint myLoc;
		private Context ctx;

		public MyLocationListener(Context ctx) {
			this.ctx = ctx;
		}

		public void onLocationChanged(Location argLocation) {
			myLoc = new GeoPoint((int) (argLocation.getLatitude() * 1000000),
					(int) (argLocation.getLongitude() * 1000000));
			if (onMap) {
				GetSongsTask getSongsTask = new GetSongsTask(ctx);
				getSongsTask.execute();
				map.getController().animateTo(myLoc);
			}

		}

		public void onProviderDisabled(String provider) {

		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}

	public GeoPoint getMyLocation() {
		return locationOverlay.getMyLocation();
	}

	public void makeSongsOverlay(ArrayList<Song> songs) {

		Drawable marker = getResources().getDrawable(
				android.R.drawable.ic_delete);

		marker.setBounds(0, 0, marker.getIntrinsicWidth(),
				marker.getIntrinsicHeight());
		if (songs == null)
			return;
		if (map.getOverlays().size() <= 1)
			map.getOverlays().add(new SongsOverlay(marker, this, songs));
		else if (songs.size() != 0) {
			map.getOverlays().set(1, new SongsOverlay(marker, this, songs));
		} else {
			map.getOverlays().remove(1);
		}

	}

}
